package com.cgc.shop.service;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;

import com.cgc.shop.model.Category;
import com.cgc.shop.utils.HibernateSessionFactory;

@Service("categoryService")
public class CategoryServiceImpl implements CategoryService {
	
	@Resource
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public void saveCategory(Category category) {
		Session session = HibernateSessionFactory.getSession();
		try {
			session.getTransaction().begin();
			session.save(category);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();  
            throw new RuntimeException(e);
		} finally {
			HibernateSessionFactory.closeSession();
		}
		
	}

	@Override
	public void updateCategory(Category category) {
		getSession().update(category);
	}

}
